package com.uaf.vxalipaybill.provider.action.v1;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.uaf.common.date.utils.DateUtils;
import com.uaf.common.file.FileOperateUtil;
import com.uaf.log.MySlf4j;
import com.uaf.vxalipaybill.provider.config.Config;
import com.uaf.vxalipaybill.provider.service.write.IVxAlipayBillWriteService;

/**
 * @filename VxAlipayBillAction.java
 * @description 微信支付宝账单
 * @author 马庆智
 * @date 2021/9/6 12:06
 */
@RestController
@RequestMapping("/v1")
public class VxAlipayDownLoadBillAction {
	public static final int cache = 10 * 1024;
	@Autowired
	private IVxAlipayBillWriteService vxAlipayBillWriteService;

	@Autowired
	private Config config;

	/**
	 * 功能描述 下载邮件
	 * @param
	 * @return void
	 * @author 马庆智
	 * @date 2021/12/1 9:19
	 */
	@PostMapping("/downloadVxMail")
	public void downloadVxMail() throws Exception {
		int i = 0;
		String localUrl = config.localUrl + "/DownloadTxt.txt";
		/**轮询下载10次*/
		for (int number = 1; number < 11; number++) {
			InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream(localUrl), "utf-8");
			BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
			String str = "";
			while (StringUtils.isNotBlank(str = bufferedReader.readLine())) {
				i += 1;
				CloseableHttpClient client = null;
				CloseableHttpResponse response = null;
				try {
					/**httpclient通过url远程下载*/
					client = HttpClients.createDefault();
					HttpGet httpget = new HttpGet(str);
					response = client.execute(httpget);
					HttpEntity entity = response.getEntity();
					InputStream is = entity.getContent();

					FileOperateUtil.fileWrite(is, config.downloadUrl + "/" + DateUtils.getTime() + "/VX-" + i +
							".zip");

					MySlf4j.textInfo("href的值为:{0},下载的压缩包名称为:{1}", str, "/VX_" + i + ".zip");
				} catch (Exception e) {
					MySlf4j.textError("下载异常");
				} finally {
					client.close();
					response.close();
				}
			}
			bufferedReader.close();
		}
	}

	/**
	 * 功能描述  根据url下载文件，保存到filepath中
	 * @param url
	 * @param diskUrl
	 * @return java.lang.String
	 * @author 马庆智
	 * @date 2021/11/25 15:41
	 */
	public static String download(String url, String diskUrl, String zipName) throws Exception {
		String filepath = "";
		String filename = "";
		CloseableHttpClient client = null;
		CloseableHttpResponse response = null;
		try {
			/**httpclient通过url远程下载*/
			client = HttpClients.createDefault();
			HttpGet httpget = new HttpGet(url);
			response = client.execute(httpget);
			HttpEntity entity = response.getEntity();
			InputStream is = entity.getContent();
			if (StringUtils.isBlank(filepath)) {
				Map<String, String> map = getFilePath(response, url, diskUrl, zipName);
				filepath = map.get("filepath");
				filename = map.get("filename");
			}
			File file = new File(filepath);
			file.getParentFile().mkdirs();
			FileOutputStream fileout = new FileOutputStream(file);
			byte[] buffer = new byte[cache];
			int ch = 0;
			while ((ch = is.read(buffer)) != -1) {
				fileout.write(buffer, 0, ch);
			}
			is.close();
			fileout.flush();
			fileout.close();

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			client.close();
			response.close();
		}
		return filepath;
	}

	/**
	 * 功能描述 获取response要下载的文件的路径
	 * @param response
	 * @param url
	 * @param diskUrl
	 * @return map
	 * @author 马庆智
	 * @date 2021/11/25 15:42
	 */
	public static Map<String, String> getFilePath(HttpResponse response, String url, String diskUrl, String zipName) {
		Map<String, String> map = new HashMap<>();
		String filepath = diskUrl;
		String filename = zipName;
		if (filename != null) {
			filepath += filename;
		}
		map.put("filename", filename);
		map.put("filepath", filepath);
		return map;
	}

}


